package com.yaohj.web.controller;

import com.yaohj.entity.MyUserDetail;
import com.yaohj.entity.User;
import com.yaohj.service.UserService;
import com.yaohj.service.jwt.JwtServiceImpl;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/users")
@Log4j2
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtServiceImpl jwtServiceImpl;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("login")
    public String login(String username, String password) {
        System.out.println("=== login ===" );
        MyUserDetail user = userService.getUserByUsername(username);
        String token = null;
        //验证密码是否正确
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username,password);
        try {
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            if(authenticate==null){
                throw new RuntimeException("用户名或密码错误");
            }
            token = jwtServiceImpl.generateToken(user);
            System.out.println("token = " + token);
            String refreshToken = jwtServiceImpl.generateRefreshToken(token);
            System.out.println("refreshToken = " + refreshToken);
        }catch (Exception e){
            log.error("用户名或密码错误!",e);
            throw new RuntimeException("用户名或密码错误");
        }
        return token;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }

    @GetMapping("redisson")
    public String redisson() {
        RBucket<String> bucket = redissonClient.getBucket("k1",  new StringCodec(StandardCharsets.UTF_8));
        bucket.set("姚浩杰好棒");
        return bucket.get();
    }
}
